<?php

class ZendBlog_Auth_Acl extends Zend_Controller_Plugin_Abstract {

    protected $_auth = null;
    protected $_acl = null;

    public function __construct(Zend_Auth $auth, Zend_Acl $acl) {
        $this->_auth = $auth;
        $this->_acl = $acl;
    }

    public function preDispatch(Zend_Controller_Request_Abstract $request) {
        // Before you lot start, this is the laziest possible
        // means of assigning roles. Hands up – I’m guilty!
        // Store to the Author table if you prefer.
        if ($this->_auth->hasIdentity()) {
            $role = 'author';
        } else {
            $role = 'guest';
        }

        // Mapping to determine which Resource the current
        // request refers to (really simple for this example!)
        $resource = $request->module;

        if (!$this->_acl->has($resource)) {
            $resource = null;
        }

        // ACL Access Check
        if (!$this->_acl->isAllowed($role, $resource)) {
            if ($this->_auth->hasIdentity()) {
                // authenticated, denied access, forward to index
                $request->setModuleName('default');
                $request->setControllerName('index');
                $request->setActionName('index');
            } else {
                // not authenticated, forward to login form
                $request->setModuleName('default');
                $request->setControllerName('auth');
                $request->setActionName('login');
            }
        }
    }

}